/**
 *
 * Copyright 2010 TeleNav, Inc. All rights reserved.
 * EntryView.java
 *
 */
package com.telenav.module.activitylist;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.telenav.app.R;
import com.telenav.framework.network.HostProvider;
import com.telenav.mvc.AbstractBaseView;
import com.telenav.ui.AndroidDialog;
import com.telenav.ui.AndroidUiHelper;
import com.telenav.ui.AndroidView;
import com.telenav.ui.CommandEvent;
import com.telenav.ui.UiEvent;
import com.telenav.ui.widget.ActionBar;
import com.telenav.ui.widget.ActionBar.ActionOnClickListener;
import com.telenav.ui.widget.ActionBar.IntentAction;
import com.telenav.util.AsyncImageLoader;

class ActivityListView extends AbstractBaseView implements IActivityListConstants, OnScrollListener
{
	private List<Map<String, Object>> mData = null;
	private int visibleLastIndex = 0;
	private int focusIndex;
	private String time;
	private String place2;
	private String[] images;
	
	private View loadMoreView;
	private SimpleAdapter adapter = null;
	private ProgressBar bar = null;
	private ListView list = null;
	private Context context;
	
    public ActivityListView(Context context)
    {
    	this.context = context;
    }

	@Override
	protected AndroidDialog createDialogDelegate(int state) {
		AndroidDialog dialog = null;
        switch (state)
        {
//            case STATE_GOTO_HOME:
//            {
//                break;
//            }
            default:
                break;
        }
        
        return dialog;
	}

	@Override
	protected boolean updateDialog(int state, AndroidDialog dialog) {
		
		return false;
	}

	@Override
	protected AndroidView createViewDelegate(int state) {
        switch(state)
        {
            case STATE_INIT:
            {
                return createActivityListView(state);
            }
            case STATE_ACTIVITYDETAIL:
            {
            	return createActivityDetailView(state);
            }
            case STATE_GALLERY:
            {
            	return createGallery(state);
            }
            case STATE_INVITATION:
            {
            	return createInvitation(state);
            }
        }
        return null;
	}

	@Override
	protected boolean updateViewDelegate(int state, AndroidView view) {
        switch(state)
        {
            case STATE_INIT:
            {
            	updateList();
                return true;
            }
            case STATE_ACTIVITYDETAIL:
            {
            	updateDetail(view);
            	return true;
            }
        }
        return false;
	}
	
	@SuppressWarnings("unchecked")
	private AndroidView createActivityListView(int state)
	{
        View fullView = View.inflate(context, R.layout.yy_activitylist, null);
        
		ActionBar actionBar = (ActionBar) fullView.findViewById(R.id.actionbar);
		actionBar.setTitle("活动列表");
        
		loadMoreView = View.inflate(context, R.layout.loadmore, null);
		final TextView loadMoreButton = (TextView)loadMoreView.findViewById(R.id.loadMoreButton);
		
		bar = (ProgressBar)fullView.findViewById(R.id.progressBar1);
        
		mData = (List<Map<String, Object>>) model.get(KEY_O_ACTIVITY_DATA);
		
        adapter = new SimpleAdapter(context, mData, R.layout.activitylist_row,
                new String[]{"title", "time", "place1", "place2", "count", "residual_cnt", "img"},
                new int[]{R.id.title, R.id.time, R.id.place1, R.id.place2, R.id.count, R.id.residual_cnt, R.id.img})
        {
			@Override
			public void setViewImage(ImageView v, String value) 
			{
                if(v.getId() == R.id.img)
                {
                	AsyncImageLoader.getInstance().loadImage(value, v, R.drawable.noimage);
                }
                else
                {
                	super.setViewImage(v, value);
                }
			}
        	
        };

		loadMoreButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				model.put(KEY_I_START_INDEX, 1 + visibleLastIndex);
				model.put(KEY_I_END_INDEX, ITEM_SIZE_PER_PAGE + visibleLastIndex);
				
				CommandEvent commandEvent = new CommandEvent(CMD_GET_ACTIVITYLIST);
				UiEvent event = new UiEvent(UiEvent.TYPE_COMMAND_EVENT);
				event.setCommandEvent(commandEvent);
				ActivityListView.this.handleUiEvent(event);
			}
		});

		list = (ListView)fullView.findViewById(R.id.mylist);
		list.addFooterView(loadMoreView);
        list.setAdapter(adapter);
        list.setOnScrollListener(this);
        list.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> paramAdapterView,
					View v, int position, long id) 
			{
				TextView timeView = (TextView)v.findViewById(R.id.time);
				TextView place2View = (TextView)v.findViewById(R.id.place2);
				
				time = timeView.getText().toString();
				place2 = place2View.getText().toString();
				model.put(KEY_I_SELECT_ID, position + 1);
				
				CommandEvent commandEvent = new CommandEvent(CMD_GOTO_ACTIVITYDETAIL);
				UiEvent event = new UiEvent(UiEvent.TYPE_COMMAND_EVENT);
				event.setCommandEvent(commandEvent);
				ActivityListView.this.handleUiEvent(event);
			}
        });
		
		return new AndroidView(fullView);
	}
	
	private AndroidView createActivityDetailView(int state)
	{
		View fullView = View.inflate(context, R.layout.activitydetail, null);

		Gallery g = (Gallery) fullView.findViewById(R.id.detail_activity_gallery);
		alignGalleryToLeft(g);
		g.setAdapter(new ImageAdapter(context, new String[]{}, ImageAdapter.SMALL_GALLERY));
        g.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
            {
            	focusIndex = position;
				CommandEvent commandEvent = new CommandEvent(CMD_GOTO_GALLERY);
				UiEvent event = new UiEvent(UiEvent.TYPE_COMMAND_EVENT);
				event.setCommandEvent(commandEvent);
				ActivityListView.this.handleUiEvent(event);
            }
        });
        
        Button inviteBtn = (Button)fullView.findViewById(R.id.btn_invitefriend);
        inviteBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				CommandEvent commandEvent = new CommandEvent(CMD_GOTO_INVITATION);
				UiEvent event = new UiEvent(UiEvent.TYPE_COMMAND_EVENT);
				event.setCommandEvent(commandEvent);
				ActivityListView.this.handleUiEvent(event);
			}
        	
        });
		
		ActionBar actionBar = (ActionBar) fullView.findViewById(R.id.actionbar);
		actionBar.setTitle("活动详情");
		actionBar.addRightAction(new IntentAction(
				R.drawable.yy_action_bar_map, new ActionOnClickListener() {
					public void onClick() {
						CommandEvent commandEvent = new CommandEvent(CMD_GOTO_MAP);
						UiEvent event = new UiEvent(UiEvent.TYPE_COMMAND_EVENT);
						event.setCommandEvent(commandEvent);
						ActivityListView.this.handleUiEvent(event);
					}
				}));
 
		return new AndroidView(fullView);
	}
	
	private AndroidView createGallery(int state)
	{
		View fullView = View.inflate(context, R.layout.activitypictures, null);
		
        Gallery g = (Gallery) fullView.findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(context, images, ImageAdapter.BIG_GALLERY));
        g.setSelection(focusIndex);
		
		return new AndroidView(fullView);
	}
	
	private AndroidView createInvitation(int state)
	{
		View fullView = View.inflate(context, R.layout.invitefriends, null);
		
		ActionBar actionBar = (ActionBar) fullView.findViewById(R.id.actionbar);
		actionBar.setTitle("邀请好友");
		
		Button goToContactBtn = (Button)fullView.findViewById(R.id.goto_contactlist);
		goToContactBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				
			}
			
		});
		
		Button goToFriendListBtn = (Button)fullView.findViewById(R.id.goto_friendlist);
		goToFriendListBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				
			}
			
		});
		
		return new AndroidView(fullView);
	}
	
	private void alignGalleryToLeft(Gallery gallery) 
	{
		DisplayMetrics dm = new DisplayMetrics();
		AndroidUiHelper.getInstance().getActivity().getWindowManager()
				.getDefaultDisplay().getMetrics(dm);
		int galleryWidth = dm.widthPixels;
		int itemWidth = 180;
		int spacing = 20;
		int offset;
		
		if (galleryWidth <= itemWidth) {
			offset = galleryWidth / 2 - itemWidth / 2 - spacing;
		} else {
			offset = galleryWidth - itemWidth - 2 * spacing;
		}
		MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams();
		mlp.setMargins(-offset, mlp.topMargin, mlp.rightMargin, mlp.bottomMargin);
	}
	
	@SuppressWarnings("unchecked")
	private void updateList()
	{
		bar.setVisibility(View.GONE);
		
		mData = (List<Map<String, Object>>) model.get(KEY_O_ACTIVITY_DATA);
		
		adapter.notifyDataSetChanged();
	}
	
	@SuppressWarnings("unchecked")
	private void updateDetail(AndroidView view)
	{
		Hashtable<String, String> activityObj = (Hashtable<String, String>)model.get(KEY_O_ACTIVITYDETAIL);
		images = (String[])model.get(KEY_O_IMAGEARRAY);
		
		((TextView)view.getView().findViewById(R.id.activity_time)).setText(time);
		((TextView)view.getView().findViewById(R.id.activity_place)).setText(place2);
		((TextView)view.getView().findViewById(R.id.activity_des)).setText(activityObj.get("overview"));
		((TextView)view.getView().findViewById(R.id.organizer)).setText(activityObj.get("organizer"));
		((Gallery)view.getView().findViewById(R.id.detail_activity_gallery)).setAdapter(new ImageAdapter(context, images, ImageAdapter.SMALL_GALLERY));
		((WebView)view.getView().findViewById(R.id.webview_content)).loadUrl(HostProvider.getHtmlUrl()+"/" + activityObj.get("detail"));
	}
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
		if (model.getInt(KEY_I_DATA_SIZE) != -1 && (totalItemCount == model.getInt(KEY_I_DATA_SIZE) + 1)) {
			model.put(KEY_B_IS_FINISH, true);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
	
    public class ImageAdapter extends BaseAdapter 
    {
        private Context mContext;
        private String[] mImages;
        private int iType;
        public final static int SMALL_GALLERY = 1;
        public final static int BIG_GALLERY = 2;
        
        public ImageAdapter(Context c, String[] images, int type) 
        {
            mContext = c;
            mImages = images;
            iType = type;
        }

        public int getCount() 
        {
            return mImages.length;
        }

        public Object getItem(int position) 
        {
            return position;
        }

        public long getItemId(int position) 
        {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) 
        {
            ImageView iv = new ImageView(mContext);
            switch(iType)
            {
            case SMALL_GALLERY:
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                iv.setLayoutParams(new Gallery.LayoutParams(180, 180));
                iv.setAdjustViewBounds(true);
            	break;
            case BIG_GALLERY:
            	iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                iv.setLayoutParams(new Gallery.LayoutParams(Gallery.LayoutParams.FILL_PARENT,
        				Gallery.LayoutParams.FILL_PARENT));
            	break;
            }
			AsyncImageLoader.getInstance().loadImage(
					HostProvider.getImageUrl() + "/" + mImages[position], iv,
					R.drawable.noimage1);
            return iv;
        }
    }
}


